/**
 * 工具类
 * author: Wanghui <wangh@ciqtek.com>
 * company: ubiot.cn
 * date: 2019-08-10
 */

import Cookies from 'js-cookie'
import { cookieExpires } from '@/common/config' // cookie保存的天数

/**
 * @Author: wh.<576649401@qq.com>
 * @msg: 存取token
 * @param {string} token
 */
export const TOKEN_KEY: string = 'token'

export const setToken = (token: string) => {
  Cookies.set(TOKEN_KEY, token, { expires: cookieExpires || 1 })
}

export const getToken = () => {
  const token = Cookies.get(TOKEN_KEY)
  if (token) {
    return token
  } else {
    return false
  }
}

export const removeToken = () => {
  Cookies.remove(TOKEN_KEY)
}

/**
 * For $confirm中的title类型无法传string的问题，使用此方法获取默认类型VNode
 * @param {string} text
 * @private
 * @return {VNode}
 */
export const _getDefaultVNode = (text: string) => {
  return {
    text,
    isRootInsert: false,
    isComment: false
  }
}

/**
 * setCookie
 *
 * @export
 * @param {string} name
 * @param {string} value
 * @param {number} [expiredays=365]
 */
export function setCookie(name: string, value: string, expiredays = 365) {
  const exdate = new Date()
  exdate.setDate(exdate.getDate() + expiredays)
  document.cookie = `${name}=${escape(value)};expires=${exdate.toUTCString()}`
}

/**
 * getCookie
 *
 * @export
 * @param {string} name
 * @returns
 */
export function getCookie(name: string) {
  if (document.cookie.length > 0) {
    let cStart = document.cookie.indexOf(name + '=')
    if (cStart !== -1) {
      cStart = cStart + name.length + 1
      let cEnd = document.cookie.indexOf(';', cStart)
      if (cEnd === -1) {
        cEnd = document.cookie.length
      }
      return unescape(document.cookie.substring(cStart, cEnd))
    }
  }
  return ''
}
